﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using BlackBird.Models;
using BlackBird.ControllerHelpers;
using BlackBird.Resources;
using BlackBird.DataAccess;

namespace BlackBird.Controllers
{
	public partial class AccountController : Controller
	{

		//
		// GET: /Account/LogOn

		public virtual ActionResult LogOn()
		{
			if (HttpContext.Request.Browser.Browser == "IE")
				return RedirectToAction("SupportedBrowser", "Account");
			return View();
		}

		public virtual ActionResult SupportedBrowser()
		{
			return View();
		}

		//
		// POST: /Account/LogOn

		[HttpPost]
		public virtual ActionResult LogOn(LogOnModel model, string returnUrl)
		{
			if (ModelState.IsValid)
			{
				user CurrentUser = null;
				if (AccountHelper.ValidateUser(model.UserName, model.Password, out CurrentUser))
				{
					FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
					if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
						&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
					{
						return Redirect(returnUrl);
					}
					else
					{
						//Save the current logged in user info.
						AccountHelper.AddAccountInfo(this, CurrentUser);
						return RedirectToAction("Index", "Home");
					}
				}
				else
				{
					ModelState.AddModelError("", BBStrings.UserNameOrPasswordWrong);
				}
			}

			// If we got this far, something failed, redisplay form
			return View(model);
		}

		//
		// GET: /Account/LogOff

		public virtual ActionResult LogOff()
		{
			FormsAuthentication.SignOut();

			return RedirectToAction("LogOn", "Account");
		}

		//
		// GET: /Account/Register

		public virtual ActionResult Register()
		{
			return View();
		}

		//
		// POST: /Account/Register

		[HttpPost]
		public virtual ActionResult Register(RegisterModel model)
		{
			if (ModelState.IsValid)
			{
				// Attempt to register the user
				MembershipCreateStatus createStatus;
				Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

				if (createStatus == MembershipCreateStatus.Success)
				{
					FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
					return RedirectToAction("Index", "Home");
				}
				else
				{
					ModelState.AddModelError("", ErrorCodeToString(createStatus));
				}
			}

			// If we got this far, something failed, redisplay form
			return View(model);
		}

		//
		// GET: /Account/ChangePassword

		[Authorize]
		public virtual ActionResult ChangePassword()
		{
			ChangePasswordModel cp = new ChangePasswordModel();
			return PartialView(MVC.Shared.Views.Util.PasswordView,cp);
		}

		//
		// POST: /Account/ChangePassword

		[Authorize]
		[HttpPost]
		public virtual ActionResult ChangePassword(ChangePasswordModel model)
		{
			string ret = "修改密码成功";// changePasswordSucceeded = false;

			// ChangePassword will throw an exception rather
			// than return false in certain failure scenarios.				
			try
			{
				if (model.NewPassword != model.ConfirmPassword)
				{
					ret = "新密码两次输入不一致.";
				}
				else if(model.NewPassword.Trim().Length < 6){
					ret = "密码必须大于6位.";
				}
				else
				{
					var currentuser = AccountHelper.GetCurrentUserId(this);
					AccountDataAccess.ChangeUserPassword(currentuser, model.NewPassword);
				}

			}
			catch (Exception)
			{
				ret = "修改密码失败，请稍后重试!";
			}



			// If we got this far, something failed, redisplay form
			return Json(ret, JsonRequestBehavior.AllowGet);
		}

		//
		// GET: /Account/ChangePasswordSuccess

		public virtual ActionResult ChangePasswordSuccess()
		{
			return View();
		}

		#region Status Codes
		private static string ErrorCodeToString(MembershipCreateStatus createStatus)
		{
			// See http://go.microsoft.com/fwlink/?LinkID=177550 for
			// a full list of status codes.
			switch (createStatus)
			{
				case MembershipCreateStatus.DuplicateUserName:
					return "User name already exists. Please enter a different user name.";

				case MembershipCreateStatus.DuplicateEmail:
					return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

				case MembershipCreateStatus.InvalidPassword:
					return "The password provided is invalid. Please enter a valid password value.";

				case MembershipCreateStatus.InvalidEmail:
					return "The e-mail address provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidAnswer:
					return "The password retrieval answer provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidQuestion:
					return "The password retrieval question provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.InvalidUserName:
					return "The user name provided is invalid. Please check the value and try again.";

				case MembershipCreateStatus.ProviderError:
					return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

				case MembershipCreateStatus.UserRejected:
					return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

				default:
					return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
			}
		}
		#endregion
	}
}
